package likou;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/06/19 09:02
 */
public class _25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        int num = 0;
        ListNode temp = head;
        while(temp!=null){
            num++;
            temp = temp.next;
        }
        return getHead(head,k,num-k);
    }
    //返回头节点，从下一个节点重新开始翻转
    public ListNode getHead(ListNode head, int k,int num) {
        int n = k;
        ListNode pre=null,now = head,next=null;
        ListNode wei = head;//把当前反转后的尾巴保住
        while(n>0&&now!=null){
            next = now.next;
            now.next = pre;
            pre = now;
            now = next;
            n--;
        }
        if(now!=null){
            if(num<k){
                wei.next = now;
            }else{
                wei.next = getHead(now,k,num-k);
            }
        }
        return pre;
    }
}
